<template>
  <view class="body">
    <view class="content">
            <view class="front">
                
                <view class="heat_beat">
                    <view class="heat-img-box">
                        <img class="heat-img" src="@/static/assets/img/heatbeat.png"/>
                    </view>
                    <view class="equipment-data">
                        <view>
                          <span class="big-text">{{ hrr_data.heartbeat}}</span><br>
                          <span class="small-text">心率（次/分）</span>
                        </view>
                    </view>
                </view>
    
                <view class="breathe_beat">
                    <view class="breath-img-box">
                        <img class="breath-img" src="@/static/assets/img/breathe.png" />
                    </view>
                    <view class="equipment-data">
                        <view>
                          <span class="big-text">{{ hrr_data.respiratory}}</span><br>
                          <span class="small-text">呼吸（次/分）</span>
                        </view>
                    </view>
                </view>
    
            </view>
                </view>
            <view class="count">
            	<view class="cell"> {{connected}}<text style="color: #AAAAAA;">状态</text> </view>
            	<view class="cell"> {{equipmentInfo.equipmentName }} <text style="color: #AAAAAA;">设备名称</text> </view>
    <!--        	<view class="cell"> {{equipmentInfo.equipmentUUID }} <text style="color: #AAAAAA;">设备编号</text> </view> -->
            	<view class="cell"> {{equipmentInfo.connectedAt }} <text style="color: #AAAAAA;">连接时间</text> </view>
            </view>
            <view class="charts-box1">
              <qiun-data-charts 
                type="line"
                :opts="heartOption"
                :chartData="chartData1"
              />
            </view>
    
            <view class="charts-box2">
              <qiun-data-charts 
                type="line"
                :opts="breathOption"
                :chartData="chartData2"
              />
            </view>
  </view>
</template>

<script setup lang="ts">
import useMqtt from '@/mqtt/use-mqtt';
import { markRaw, onMounted, ref } from 'vue';
import type { HrrInfo,EquipmentDetailInfo } from '@/api/types';
import { useRoute, useRouter } from 'vue-router';
import { getEquipmentDetail } from '@/api/equipment/equipment';
import { createArray } from '@/utils/array';
// import { RefSymbol } from '@vue/reactivity';
// const myHeartChart = document.getElementById('myHeartChart')
// const myHeartChartRef = ref(null); // 使用 ref 来管理元素引用
// const myHeartChart = ref<HTMLElement>()
//     let myChart = null; // 用于存储图表实例
const myHeartsChart = ref<any>()
const chartData1 = ref({});
const chartData2 = ref({});
// const myBreathChart = document.getElementById('myBreathChart')
// const myBreathChart = ref(null)
const myBreathsChart = ref<any>()

const route = useRoute()
const router = useRouter()
const equipmentUUID = "618fb722-44ca-4f62-a89f-85d5ed5e84a2"

//用来接收 原始数据并-175
let changeHeartArray:number[]=[]
let changeBreathArray:number[]=[]

//展示连接状态
let connected = "null"
// 存储展示数据
let heartBeatArray:number[] = []
let breathArray:number[]  = []
const HR_RTopic = "hrr";
const heartBeatTopic = "heartBeat";
const logTopic = "log";
const messageType = "json";
const client_uuid = "MWR_77GHz_0001";
const productName = "RPDetection";
const hrr_data = ref<HrrInfo>({} as HrrInfo)

const equipmentInfo = ref<EquipmentDetailInfo>({} as EquipmentDetailInfo)



const count = 300

const heartOption = {
  dataLabel: false, // 数据显示
  dataPointShape: true, // 圆点显示
  update:true,
  duration: 20, // 0
  animation: false,
  // enableScroll: true,
  legend: {},
  title: {
    text: '心跳信息',
    left:'center',
    fontSize: 14,
  },
  xAxis: {
    "labelCount": 10, //默认显示个数
    type: 'category',
    disableGrid: true, 
  },
  yAxis: {
    type:'value',
    gridType: "dash",
    dashLength: 2,
  },
  extra: {
    line: {
      type: "straight",
      width: 2,
      activeType: "hollow",
    },
  },
};
const breathOption = {
  dataLabel: false, // 数据显示
  dataPointShape: true, // 圆点显示
  update:true,
  duration: 20, // 0
  animation: false,
  // enableScroll: true,
    legend: {},
    title: {
      text: '呼吸信息',
      left:'center',
      fontSize: 14,
    },
    xAxis: {
      "labelCount": 10,
      type: 'category',
      disableGrid: true, 
    },
    yAxis: {
      type:'value',
      gridType: "dash",
      dashLength: 2,
    },
    extra: {
      line: {
        type: "straight",
        width: 2,
        activeType: "hollow",
      },
    },
}
const heartInit = () =>{
  // 模拟从服务器获取数据时的延时
  setTimeout(() => {
    // 模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
    const res = {
      categories: createArray(count),
      series: [
        {
          name: "心跳信息",
          data: [150,230,224,218,135,147,260],
        },
      ],
    };
    chartData1.value = JSON.parse(JSON.stringify(res));
  }, 500);
}

const breathInit = ()=>{
  // 模拟从服务器获取数据时的延时
  setTimeout(() => {
    // 模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
    const res = {
      categories: createArray(count),
      series: [
        {
          name: "呼吸信息",
          data: [150,230,224,218,135,147,260],
        },
      ],
    };
    chartData2.value = JSON.parse(JSON.stringify(res));
  }, 500);
}

/**
 * 用于拼接数据
 * @param oldArray  旧的array
 * @param addArray  新进来的array
 */
const concatArray=(oldArray:number[],addArray:number[]):number[]=>{
    let newArray:number[]=[]
    console.log(addArray)
    if(oldArray.length<=count){
        newArray=addArray.concat(oldArray)
        // newArray=oldArray.concat(addArray)
    }else{
        let temp = oldArray.slice(0,oldArray.length-20)
        newArray=addArray.concat(temp)
    }
    console.log(newArray)
    return newArray
}

/**
 * 用于处理数据,将 0-255数据减去一半 以调整坐标轴
 * @param oldArray 
 * @param newArray 
 */
const changeData=(oldArray:number[],newArray:number[])=>{
    for(let i in oldArray){
        newArray.push(oldArray[i]-127.5);
    }
}

const{startMqtt,addLink} = useMqtt();
onMounted(()=>{
    getEquipmentInfo()
    heartInit()
    breathInit()
})

const getEquipmentInfo=async()=>{
  // let token = uni.getStorageSync('token');
  // console.log(token)
    const res = await getEquipmentDetail(equipmentUUID)
    console.log(res)
    if(res.code==200){
        equipmentInfo.value=res.data
        console.log(equipmentInfo.value)
        if(equipmentInfo.value.connected){
          connected = "已连接"
        }else{
          connected = "未连接"
        }
    }else{

    }
}

const translateToHistory=(equipmentId:string)=>{
    router.push({
        path:"/equipment-history",
        query:{
            equipmentId: equipmentId
        }
    })
}



startMqtt("A",(topic,data)=>{

    const hrr_topic =HR_RTopic+"/"+productName+"/"+messageType+"/"+client_uuid
    if(topic==hrr_topic){
        const str = data.toString();//修改此处
        hrr_data.value = JSON.parse(str)
        // console.log(hrr_data.value.heartbeatArray)
        changeBreathArray=[]
        changeHeartArray=[]
        //先处理数据
        changeData(hrr_data.value.heartbeatArray,changeHeartArray)
        changeData(hrr_data.value.respiratoryArray,changeBreathArray)
        // 然后拼接
        heartBeatArray=concatArray(heartBeatArray,changeHeartArray)
        breathArray=concatArray(breathArray,changeBreathArray)
        // 最后画图
        const res1 = {
          categories: createArray(count),
          series: [
            {
              name: "心跳信息",
              data: heartBeatArray,
            },
          ],
        };
        chartData1.value = JSON.parse(JSON.stringify(res1));
        const res2 = {
          categories: createArray(count),
          series: [
            {
              name: "呼吸信息",
              data: breathArray,
            },
          ],
        };
        chartData2.value = JSON.parse(JSON.stringify(res2));
        // console.log(heartBeatArray)
        // myHeartsChart.value.setOption(heartOption)
        // myBreathsChart.value.setOption(breathOption)
        // myBreathsChart.value.setOption(breathOption)
        // console.log(hrr_data.value)
        // console.log(hrr_data.value.heartbeat)
        }
    })

    addLink('hrr/#');
        addLink('log/#');

</script>


<style lang="scss" scoped>
  .body {
      // background-color: #265A8F;
  }
.content{
	// background-color: #265A8F;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 20rpx;
}


.front{
	// background-color: #265A8F;
    display: flex;
    flex-direction: row;
    width: 90%;
    height: 30%;
    margin-bottom: 2%;
    margin-left: 13%;
}


.heartbeat-curve{
    display: flex;
    flex-flow: row;
    width: 60%;
    height: 30%;
    background-color: #FFFFFF;
    margin-bottom: 2%;
    box-shadow: 0px 1px 6px rgba(0, 0, 0, 16%);
    border-radius: 5px;
}

.breath-curve{
    display: flex;
    flex-flow: row;
    width: 60%;
    height: 30%;
    background-color: #FFFFFF;
    margin-bottom: 2%;
    box-shadow: 0px 1px 6px rgba(0, 0, 0, 16%);
    border-radius: 5px;
}


.equipment-detail{
    display: flex;
    flex-flow: column;
    width: 31%;
    height: 100%;
    background-color: #FFFFFF;
    margin-right: 3%;
    box-shadow: 0px 1px 6px rgba(0, 0, 0, 16%);
    border-radius: 5px;
    justify-content: center;
    align-items: center;
}

.heat_beat{
	// background-color: #265A8F;
    display: flex;
    flex-direction: row;
    text-align: left;
    flex: 1;
    width: 50%;
    height: 100%;
    // background-color: #FFFFFF;
    margin-right: 3%;
    margin-left: -14%;
    box-shadow: 0px 1px 6px rgba(0, 0, 0, 16%);
    border-radius: 5px;
    align-items: center;
    justify-content: center;
}

.breathe_beat{
	// background-color: #265A8F;
    display: flex;
    flex-direction: row;
    flex: 1;
    width: 50%;
    height: 100%;
    // background-color: #FFFFFF;
    margin-right: 0;
    margin-left: auto;
    box-shadow: 0px 1px 6px rgba(0, 0, 0, 16%);
    border-radius: 5px;
    align-items: center;
    justify-content: center;
}

.line{
    display: flex;
    flex-flow: row;
    font-family:'Alibaba-PuHuiTi-Medium';
    font-weight:500;
    font-size: 10px;
    color: #3969C4;
    width: 90%;
    height: 11.8%;
    justify-content: center;
    align-items: center;
    /* font-family: ''; */
}


.heat-img-box{
    display: flex;
    width: 50%;
    height: 100%;
    margin-left: 1%;
}

.breath-img-box{
    display: flex;
    width: 50%;
    height: 100%;
    margin-left: 1%;
    align-items: center;
    justify-content: center;
}
.heat-img{
	margin-left: 10%;
  width:  200rpx;
  height: 200rpx;
}
.breath-img{
    width: 200rpx;
    height: 200rpx;
}


.equipment-data{
    display: flex;
    flex: 1;
    width: 50%;
    height: 10%;
    color: #3969C4;
    font-size: 20px;
    align-items: center;
    justify-content: center;
    .big-text {
		color: #ff0000;
        font-size: 20px;
    }
    
    .small-text {
		color: #ff0000;
        font-size: 12px;
    }
}
.title{
    display: flex;
    width: 20%;
}
.value{
    display: flex;
    flex-flow: row;
    width: 80%;
}
.charts-box1 {
    width: 100%;
    height: 300px;
  }
  .charts-box2 {
    width: 100%;
    height: 300px;
  }
  .count {
  	display: flex;
  	margin: 0 20rpx;
  	height: 120rpx;
  	text-align: center;
  	border-radius: 4rpx;
  	// background-color: #265A8F;
  
  	position: relative;
  	top: 10rpx;
  
  	.cell {
  		margin-top: 10rpx;
  		flex: 1;
  		padding-top: 20rpx;
  		font-size: 27rpx;
  		color: #333;
  	}
  
  	text {
  		display: block;
  		font-size: 24rpx;
  	}
  }
// .value >span{
//     display: flex;
//     flex-flow: row;
//     justify-content: center;
//     align-items: center;
//     margin-left: 20px;
//     color: #f56c6c;
// }
</style>